package com.wuze.cloud.Interceptor;


import com.wuze.cloud.adapter.SysUserAdapter;
import com.wuze.cloud.context.UserContext;
import com.wuze.cloud.exception.SysGlobalException;
import com.wuze.cloud.pojo.SysUserDO;
import com.wuze.cloud.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.wuze.cloud.enums.SysGlobalExceptionEnum.USER_NOT_LOGIN;

/**
 * @author: wuze
 * @description:
 * @date: 2023/02/17
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserAdapter userAdapter;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        if (StringUtil.isNotBlank(token)) {
            Claims claims = null;
            try {
                claims = JwtUtil.parseJWT(token);
            } catch (Exception e) {
                log.warn("JWT格式错误");
                throw new SysGlobalException(USER_NOT_LOGIN.getCode(), USER_NOT_LOGIN.getMsg());
            }
            SysUserDO user = userAdapter.buildSysUserDO(claims);
            UserContext.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
